<template>
  <div class="tasks section-container">
    <div class="page-header">
      <h2 class="page-title">任务管理</h2>
      <p class="page-subtitle">管理和跟踪公司内部的各项工作任务，提高团队协作效率</p>
    </div>

    <div class="action-bar">
      <el-button type="primary" @click="showAddDialog" class="action-btn">添加任务</el-button>
    </div>

    <div class="content-section">
      <el-card class="data-card">
        <el-table :data="tasks" style="width: 100%" v-loading="loading">
          <el-table-column prop="title" label="任务标题" />
          <el-table-column prop="priority" label="优先级">
            <template #default="{ row }">
              <el-tag :type="getPriorityTag(row.priority)">
                {{ getPriorityText(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template #default="{ row }">
              <el-tag :type="getStatusTag(row.status)">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="deadline" label="截止日期">
            <template #default="{ row }">
              {{ row.deadline ? new Date(row.deadline).toLocaleString() : '无' }}
            </template>
          </el-table-column>
          <el-table-column prop="employeeId" label="负责人" />
          <el-table-column prop="createTime" label="创建时间">
            <template #default="{ row }">
              {{ row.createTime ? new Date(row.createTime).toLocaleString() : '' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="180">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
              <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑任务' : '添加任务'"
      width="500px"
      :modal-append-to-body="false"
      :append-to-body="true"
      align-center
      class="task-dialog"
    >
      <el-scrollbar max-height="60vh">
        <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="100px"
          class="task-form"
        >
          <el-form-item label="任务标题" prop="title">
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item label="任务内容" prop="content">
            <el-input v-model="form.content" type="textarea" :rows="4" />
          </el-form-item>
          <el-form-item label="优先级" prop="priority">
            <el-radio-group v-model="form.priority">
              <el-radio :label="1">低</el-radio>
              <el-radio :label="2">中</el-radio>
              <el-radio :label="3">高</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="form.status">
              <el-option :value="0" label="未开始" />
              <el-option :value="1" label="进行中" />
              <el-option :value="2" label="已完成" />
            </el-select>
          </el-form-item>
          <el-form-item label="截止日期" prop="deadline">
            <el-date-picker
              v-model="form.deadline"
              type="datetime"
              placeholder="选择截止日期"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="负责人ID" prop="employeeId">
            <el-input v-model="form.employeeId" />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../utils/request'

const tasks = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref(null)

const form = ref({
  title: '',
  content: '',
  priority: 1,
  status: 0,
  deadline: '',
  employeeId: null
})

const rules = {
  title: [
    { required: true, message: '请输入任务标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  content: [
    { max: 500, message: '内容长度不能超过500个字符', trigger: 'blur' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  deadline: [],
  employeeId: [
    { 
      validator: (rule, value, callback) => {
        if (value && isNaN(parseInt(value))) {
          callback(new Error('负责人ID必须是数字'));
        } else {
          callback();
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

const fetchTasks = async () => {
  loading.value = true
  try {
    console.log('开始获取任务列表, 参数:', {
      page: currentPage.value,
      pageSize: pageSize.value
    })
    
    const response = await request.get('/api/tasks/pages', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      }
    })
    
    console.log('任务列表API响应:', response)
    
    if (response.code === 200 && response.data) {
      tasks.value = response.data.records || []
      total.value = response.data.total || 0
      console.log('更新后的任务列表:', tasks.value)
    } else {
      tasks.value = []
      total.value = 0
      ElMessage.error(response.msg || '获取数据失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    ElMessage.error('获取任务列表失败')
    tasks.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  isEdit.value = false
  form.value = {
    title: '',
    content: '',
    priority: 1,
    status: 0,
    deadline: '',
    employeeId: null
  }
  dialogVisible.value = true
}

const handleEdit = (row) => {
  isEdit.value = true
  form.value = { ...row }
  dialogVisible.value = true
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该任务吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request.delete(`/api/tasks/${row.id}`)
      if (response.code === 200) {
        ElMessage.success('删除成功')
        fetchTasks()
      } else {
        ElMessage.error(response.msg || '删除失败')
      }
    } catch (error) {
      console.error('删除任务失败:', error)
      ElMessage.error('删除任务失败')
    }
  }).catch(() => {})
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 创建处理后的数据对象，确保类型和格式正确
    const taskData = {
      ...form.value,
      // 确保employeeId是数值类型
      employeeId: form.value.employeeId ? parseInt(form.value.employeeId) : null
    }
    
    // 添加日志以便调试
    console.log('提交的任务数据:', taskData)
    
    if (isEdit.value) {
      const response = await request.put('/api/tasks', taskData)
      if (response.code === 200) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchTasks()
      } else {
        ElMessage.error(response.msg || '更新失败')
      }
    } else {
      try {
        const response = await request.post('/api/tasks', taskData)
        if (response.code === 200) {
          ElMessage.success('添加成功')
          dialogVisible.value = false
          fetchTasks()
        } else {
          console.error('添加任务失败，服务器返回:', response)
          ElMessage.error(response.msg || '添加失败')
        }
      } catch (error) {
        console.error('添加任务请求错误:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status,
          statusText: error.response?.statusText
        })
        ElMessage.error(`添加失败: ${error.response?.status || error.message}`)
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
    ElMessage.error('表单验证失败，请检查输入')
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  fetchTasks()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchTasks()
}

const getPriorityText = (priority) => {
  switch (priority) {
    case 1: return '低'
    case 2: return '中'
    case 3: return '高'
    default: return '未知'
  }
}

const getPriorityTag = (priority) => {
  switch (priority) {
    case 1: return 'info'
    case 2: return 'warning'
    case 3: return 'danger'
    default: return ''
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '未开始'
    case 1: return '进行中'
    case 2: return '已完成'
    default: return '未知'
  }
}

const getStatusTag = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'warning'
    case 2: return 'success'
    default: return ''
  }
}

onMounted(() => {
  fetchTasks()
})
</script>

<style scoped>
.tasks {
  padding: 0 24px;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-title {
  font-size: 28px;
  font-weight: 500;
  margin-bottom: 12px;
  color: var(--app-text-color);
}

.page-subtitle {
  font-size: 16px;
  color: var(--app-secondary-text);
  max-width: 700px;
  margin: 0 auto 20px;
}

.action-bar {
  margin-bottom: 24px;
  display: flex;
  gap: 12px;
}

.action-btn {
  min-width: 120px;
  height: 40px;
  font-weight: 500;
}

.content-section {
  margin-bottom: 40px;
}

.data-card {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s;
}

.data-card:hover {
  box-shadow: 0 6px 30px rgba(0, 0, 0, 0.08);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.task-form {
  padding: 20px 0;
}
</style> 